﻿using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;


namespace  IOT_Tools
{
    class HTTPHelper
    {   //***************************************************************** YeeLink Http
        public string YeeLink_Http(string method, string url, string apiKey, string param)
        {
            string strValue = "";
            string strURL = url;
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = method;
            request.Headers.Set("U-ApiKey", apiKey);
            request.ContentType = "application/json;charset=UTF-8";
            //application/x-www-form-urlencoded;charset=utf-8
            //text/xml
            //text/json
            if (method.ToUpper() != "GET") {
                string paraUrlCoded = param;
                byte[] payload;
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                request.ContentLength = payload.Length;
                Stream writer = request.GetRequestStream();
                writer.Write(payload, 0, payload.Length);
                writer.Close();
            }
            HttpWebResponse response;
            try
            {   response = (HttpWebResponse)request.GetResponse();
                System.IO.Stream s;
                s = response.GetResponseStream();
                string StrDate = "";
                StreamReader Reader = new StreamReader(s, Encoding.GetEncoding("utf-8"));
                while ((StrDate = Reader.ReadLine()) != null)
                {
                    strValue += StrDate + "\r\n";
                }
                
            }
            catch(Exception e) {
                return e.Message;
            }
            strValue = Unicode2GBK(strValue); 
            return strValue;
        }
        //***************************************************************** 编码转换
        private string Unicode2GBK(string str)
        {
            return(Regex.Unescape(str));
        }
        private string GBK2Unicode(string str)
        {
            string outStr = "";
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    if (Regex.IsMatch(str[i].ToString(), @"[\u4e00-\u9fa5]")) { outStr += "\\u" + ((int)str[i]).ToString("x"); }
                    else { outStr += str[i]; }
                }
            }
            return outStr;
        }
        //*****************************************************************
    }
}
